﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using Pyco.Framework;
namespace AutoSendMail
{
    class EmailChecker
    {
        NetworkStream SMTPNetworkStream;
        StreamReader SMTPStreamReader;
        StreamWriter SMTPStreamWriter;
        DateTime TimeOutCheck;
        String EmailFrom = "sonleduc_99@yahoo.com";
        private int TimeOut = 2; //second

        public bool isValidEmailAddress(String emailAddress, ref String resultText)
        {
            bool valid = false;
            resultText = "invalid Email Address";
            emailAddress = emailAddress.Trim();

            if (!Utility.IsValidEmailFormat(emailAddress))
            {
                resultText = "Invalid Email Format";
                return false;
            }


            String domain = emailAddress.Substring(emailAddress.IndexOf("@") + 1, emailAddress.Length - emailAddress.IndexOf("@") - 1);
            switch (domain)
            {
                case "gmail.com":
                    {
                        valid = isValidGmailEmail(emailAddress);
                        if (valid)
                            resultText = "OK";
                        break;
                    }
                case "yahoo.com":
                    {
                        valid = isValidYahooEmail(emailAddress);
                        if (valid)
                            resultText = "OK";
                        break;
                    }
                case "yahoo.com.vn":
                    {
                        valid = isValidYahooVNEmail(emailAddress);
                        if (valid)
                            resultText = "OK";
                        break;
                    }
                default:
                    {
                        resultText = "Not support this Domain";
                        break;
                    }

            }
            return valid;
        }

        private bool WaitForResponse(string Code)
        {
            // Get the time at connecting moment
            TimeOutCheck = DateTime.Now;
            // Span the timer
            TimeSpan TimeSpanner = DateTime.Now - TimeOutCheck;
            // Loop until timeout exceeds
            while (TimeSpanner.Seconds < TimeOut)
            {
                if (SMTPNetworkStream.DataAvailable)
                {
                    // If catch the incoming data, get it by lines
                    string DataIn = SMTPStreamReader.ReadLine();
                    Logger.Info(DataIn);
                    // Check for the sufficient response code
                    if (DataIn.Substring(0, Code.Length).Equals(Code))
                        return true;
                }
                // Recalculate timeout
                TimeSpanner = DateTime.Now - TimeOutCheck;
            }
            // Return false if it fails
            return false;
        }

        public bool isValidGmailEmail(string gmailAddress)
        {
            TcpClient SMTPTCPClient = new TcpClient();
            // Set up the connection
            try
            {
                Logger.Info(String.Format("> telnet {0} {1}", "telnet alt1.gmail-smtp-in.l.google.com", "25"));
                SMTPTCPClient.Connect("alt1.gmail-smtp-in.l.google.com", 25);
            }
            catch (Exception ex)
            {
                // if fail to connect to mail server
                Logger.Error("Error: " + ex.Message);
                return false;
            }
            // If succeed creating the connection
            // init all the streams
            SMTPNetworkStream = SMTPTCPClient.GetStream();
            SMTPStreamReader = new StreamReader(SMTPNetworkStream);
            SMTPStreamWriter = new StreamWriter(SMTPNetworkStream);

            // Need for server's response
            if (WaitForResponse("220"))
            {
                // Greet mail server
                Logger.Info(String.Format("> {0}","helo u"));
                SMTPStreamWriter.WriteLine("helo u");
                // Clear the rest/garbage
                SMTPStreamWriter.Flush();
            }
            else // if no response from server
            {
                // connection fails
                SMTPTCPClient.Close();
                return true;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.WriteLine(String.Format("MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> RCPT TO: <{0}>", gmailAddress));
                SMTPStreamWriter.WriteLine(String.Format("RCPT TO: <{0}>",gmailAddress)); 
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                Logger.Info("> DATA");
                SMTPStreamWriter.WriteLine("DATA");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("354"))
            {
                Logger.Info(String.Format("> Subject: {0}", " "));
                SMTPStreamWriter.WriteLine(String.Format("Subject: {0}", " "));
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> .");
                SMTPStreamWriter.WriteLine(".");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                return true;
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }
            return false;
        }

        public bool isValidYahooEmail(string yahooEmailAddress)
        {
            TcpClient SMTPTCPClient = new TcpClient();
            // Set up the connection
            try
            {
                Logger.Info(String.Format("> telnet {0} {1}", "telnet mta5.am0.yahoodns.net", "25"));
                SMTPTCPClient.Connect("mta5.am0.yahoodns.net", 25);
            }
            catch (Exception ex)
            {
                // if fail to connect to mail server
                Logger.Error("Error: " + ex.Message);
                return false;
            }
            // If succeed creating the connection
            // init all the streams
            SMTPNetworkStream = SMTPTCPClient.GetStream();
            SMTPStreamReader = new StreamReader(SMTPNetworkStream);
            SMTPStreamWriter = new StreamWriter(SMTPNetworkStream);

            // Need for server's response
            if (WaitForResponse("220"))
            {
                // Greet mail server
                Logger.Info(String.Format("> {0}", "helo u"));
                SMTPStreamWriter.WriteLine("helo u");
                // Clear the rest/garbage
                SMTPStreamWriter.Flush();
            }
            else // if no response from server
            {
                // connection fails
                SMTPTCPClient.Close();
                return true;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.WriteLine(String.Format("MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> RCPT TO: <{0}>", yahooEmailAddress));
                SMTPStreamWriter.WriteLine(String.Format("RCPT TO: <{0}>", yahooEmailAddress));
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                Logger.Info("> DATA");
                SMTPStreamWriter.WriteLine("DATA");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("354"))
            {
                Logger.Info(String.Format("> Subject: {0}", " "));
                SMTPStreamWriter.WriteLine(String.Format("Subject: {0}", " "));
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> .");
                SMTPStreamWriter.WriteLine(".");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                return true;
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            return false;
        }

        public bool isValidYahooVNEmail(String yahooVnEmail)
        {
            TcpClient SMTPTCPClient = new TcpClient();
            // Set up the connection
            try
            {
                Logger.Info(String.Format("> telnet {0} {1}", "mx1.mail.sg1.yahoo.com", "25"));
                SMTPTCPClient.Connect("mx1.mail.sg1.yahoo.com", 25);
            }
            catch (Exception ex)
            {
                // if fail to connect to mail server
                Logger.Error("Error: " + ex.Message);
                return false;
            }
            // If succeed creating the connection
            // init all the streams
            SMTPNetworkStream = SMTPTCPClient.GetStream();
            SMTPStreamReader = new StreamReader(SMTPNetworkStream);
            SMTPStreamWriter = new StreamWriter(SMTPNetworkStream);

            // Need for server's response
            if (WaitForResponse("220"))
            {
                // Greet mail server
                Logger.Info(String.Format("> {0}", "helo u"));
                SMTPStreamWriter.WriteLine("helo u");
                // Clear the rest/garbage
                SMTPStreamWriter.Flush();
            }
            else // if no response from server
            {
                // connection fails
                SMTPTCPClient.Close();
                return true;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.WriteLine(String.Format("MAIL FROM: <{0}>", EmailFrom));
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                // write down the RCP address
                Logger.Info(String.Format("> RCPT TO: <{0}>", yahooVnEmail));
                SMTPStreamWriter.WriteLine(String.Format("RCPT TO: <{0}>", yahooVnEmail));
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                Logger.Info("> DATA");
                SMTPStreamWriter.WriteLine("DATA");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("354"))
            {
                Logger.Info(String.Format("> Subject: {0}", " "));
                SMTPStreamWriter.WriteLine(String.Format("Subject: {0}", " "));
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> ");
                SMTPStreamWriter.WriteLine(" ");
                SMTPStreamWriter.Flush();

                Logger.Info("> .");
                SMTPStreamWriter.WriteLine(".");
                SMTPStreamWriter.Flush();
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            // Response for input RCP Address
            if (WaitForResponse("250"))
            {
                return true;
            }
            else
            {
                // close the connection otherwise
                SMTPTCPClient.Close();
                return false;
            }

            return false;
        }

    }
}
